package 多线程08_lock对象;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName: TestThreadLock01
 * @Author: AllenSun
 * @Date: 2022/3/23 下午10:53
 */
public class TestThreadTrylock {

    public static String nowTime() {
        return new SimpleDateFormat("HH:mm:ss").format(new Date());
    }

    public static void log(String msg) {
        System.out.printf("%s %s %s %n",nowTime(),Thread.currentThread().getName(),msg);
    }

    public static void main(String[] args) {
        Lock lockDemo = new ReentrantLock();

        Thread thread1 = new Thread() {
            public void run() {
                boolean lockResult = false;
                try {
                    log("线程启动");
                    log("试图占有对象：lock");
                    lockResult = lockDemo.tryLock(1, TimeUnit.SECONDS);
                    if(lockResult){
                        log("占有对象：lock");
                        log("进行5秒的业务操作");
                        Thread.sleep(5000);
                    } else {
                        log("经过1秒钟的努力，还没有占有对象，放弃占有");
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if(lockResult){
                        log("释放对象：lock");
                        lockDemo.unlock();
                    }
                }
                log("线程结束");
            }
        };
        thread1.setName("thread01");
        thread1.start();


        try {
            //先让t1飞2秒
            Thread.sleep(2000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }


        Thread thread2 = new Thread() {
            public void run() {
                boolean lockResult = false;
                try {
                    log("线程启动");
                    log("试图占有对象：lock");
                    lockResult = lockDemo.tryLock(1, TimeUnit.SECONDS);
                    if(lockResult){
                        log("占有对象：lock");
                        log("进行5秒的业务操作");
                        Thread.sleep(5000);
                    } else {
                        log("经过1秒钟的努力，还没有占有对象，放弃占有");
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if(lockResult){
                        log("释放对象：lock");
                        lockDemo.unlock();
                    }
                }
                log("线程结束");
            }
        };
        thread2.setName("thread02");
        thread2.start();


    }
}
